package org.jeecgframework.web.controller;


import org.jeecgframework.core.util.ResourceUtil;
import org.jeecgframework.core.util.StringUtil;
import org.jeecgframework.core.util.oConvertUtils;
import org.jeecgframework.web.service.*;
import org.jeecgframework.web.system.pojo.base.*;
import org.jeecgframework.web.system.pojo.vo.ProcurementNote;
import org.jeecgframework.web.system.pojo.vo.ShoppingCar;
import org.jeecgframework.web.system.service.SystemService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;

import java.util.ArrayList;
import java.util.List;

/**
 * Created by red on 2016/9/1.
 * 购物车
 */
@Controller
@RequestMapping("/shoppingcar")
public class CbsShoppingCarController {

    @Autowired
    private CbsShoppingCarServiceI shoppingCarService;

    @Autowired
    private SystemService systemService;

    @Autowired
    private ZyContactsServiceI zyContactsService;

    @Autowired
    private CbsInvoiceInfoServiceI cbsInvoiceInfoService;

    @Autowired
    private ZyCommonAddressServiceI zyCommonAddressService;

    @Autowired
    private WxCommonService wxCommonService;

    private static final String WX_PREFIX = "com/wx/added_product/";




    /**
     * 获取登录用户的购物车信息
     * */
    @RequestMapping(params = "getCarInfo",method = {RequestMethod.GET})
    @ResponseBody
    public ShoppingCar getShoppingCar(HttpServletRequest request){
        if(null != ResourceUtil.getSessionUserName() && ResourceUtil.getSessionUserName().ifGoldMedal()){
            return shoppingCarService.generateShoppingCar(ResourceUtil.getSessionUserName().getUserName());
        }else{
            String openId = (String)request.getSession().getAttribute("openId");
            if(StringUtil.isNotEmpty(openId)){
                return shoppingCarService.generateShoppingCarWithOpenId(openId);
            }
            return new ShoppingCar();
        }
    }



    @RequestMapping(params = "addProduct")
    @ResponseBody
    public ShoppingCar addProduct(String partId,int num,HttpServletRequest request){
        TSUser user = ResourceUtil.getSessionUserName();
        if(user != null && user.ifGoldMedal() ){
            shoppingCarService.addProductToShoppingCar(partId,num);
            return shoppingCarService.generateShoppingCar(ResourceUtil.getSessionUserName().getUserName());
        }else{
        	String openId = oConvertUtils.getString(request.getSession().getAttribute("openId"));
            shoppingCarService.addProductToShoppingCar(partId,num,openId);
            return shoppingCarService.generateShoppingCarWithOpenId(openId);
        }
    }

    @RequestMapping(params = "delCarItem")
    @ResponseBody
    public ShoppingCar delCarItem(String partId,int num,HttpServletRequest request){
        TSUser user = ResourceUtil.getSessionUserName();
        if(user != null && user.ifGoldMedal()){
            shoppingCarService.reduceShoppingCar(partId,num,ResourceUtil.getSessionUserName().getUserName());
            return shoppingCarService.generateShoppingCar(ResourceUtil.getSessionUserName().getUserName());
        }else{
            String openId = oConvertUtils.getString(request.getSession().getAttribute("openId"));
            shoppingCarService.reduceShoppingCar(partId,num,openId);
            return shoppingCarService.generateShoppingCarWithOpenId(openId);
        }

    }

    @RequestMapping(params = "updateCarItem")
    @ResponseBody
    public ShoppingCar updateCarItem(String partId,int num,HttpServletRequest request){
        TSUser user = ResourceUtil.getSessionUserName();
        if(null != user && user.ifGoldMedal()){
            shoppingCarService.updateProductNum(partId,num,user.getUserName());
            return shoppingCarService.generateShoppingCar(user.getUserName());
        }else{
            String openId = oConvertUtils.getString(request.getSession().getAttribute("openId"));
            shoppingCarService.updateProductNum(partId,num,openId);
            return shoppingCarService.generateShoppingCarWithOpenId(openId);
        }

    }

    @RequestMapping(params = "itemCheck")
    @ResponseBody
    public ShoppingCar itemCheck(String itemId,int checkStatus,HttpServletRequest request){
        CbsShoppingCartEntity shoppingCar = shoppingCarService.get(CbsShoppingCartEntity.class,itemId);
        if(StringUtil.isNotEmpty(shoppingCar)){
            shoppingCar.setCheckStatus(checkStatus);
            shoppingCarService.saveOrUpdate(shoppingCar);
        }
        TSUser user = ResourceUtil.getSessionUserName();
        return null != user && user.ifGoldMedal()?shoppingCarService.generateShoppingCar(user.getUserName()):shoppingCarService.generateShoppingCarWithOpenId(oConvertUtils.getString(request.getSession().getAttribute("openId")));
    }

    @RequestMapping(params = "goBuy")
    public String itemCheck(String commonAddressId,String invoiceId,ModelMap modelMap,HttpServletRequest request){
        String toUrl = "procurement/buy";
        TSUser user = ResourceUtil.getSessionUserName();
        //金牌会员
        if(null != user && user.ifGoldMedal()){
            ZyCommonAddressEntity address = null;
            if(StringUtil.isNotEmpty(commonAddressId)){
                address = shoppingCarService.get(ZyCommonAddressEntity.class,commonAddressId);

            }else{
                address = zyCommonAddressService.getDefaultAddress(ResourceUtil.getSessionUserName().getUserName());
            }
            if(StringUtil.isNotEmpty(invoiceId)){
                CbsInvoiceInfoEntity invoice = shoppingCarService.get(CbsInvoiceInfoEntity.class,invoiceId);
                modelMap.put("invoice",invoice);

            }
            modelMap.put("address",address);
            List<ZyContactsEntity> contacts = shoppingCarService.findHql("from ZyContactsEntity where tsBaseUser.id='"+ResourceUtil.getSessionUserName().getId()+"'");
            if(contacts != null && contacts.size() > 0){
                ZyContactsEntity ct = contacts.get(0);
                modelMap.put("contact",ct);
                if(StringUtil.isNotEmpty(ct.getBelongCinema())){
                    List<ZyEquipmentSpareEntity> equips = shoppingCarService.findHql("from ZyEquipmentSpareEntity where zyCinema.id=?",ct.getBelongCinema().getId());
                    modelMap.put("equips",equips);
                }
            }
        }else{
           toUrl = "procurement/buy-open";
        }

        return WX_PREFIX+toUrl;
    }

    @RequestMapping(params = "goInvoice")
    public String goInvoice(ModelMap map){
    	List<ZyContactsEntity> contacts = shoppingCarService.findHql("from ZyContactsEntity where tsBaseUser.id='"+ResourceUtil.getSessionUserName().getId()+"'");
        if(contacts != null && contacts.size() > 0){
            ZyContactsEntity ct = contacts.get(0);
            if(StringUtil.isNotEmpty(ct.getBelongCinema())){
                map.put("cinema",ct.getBelongCinema().getId());
            } else {
            	map.put("cinema",null);
            }
        }
        map.put("ordInvoice", cbsInvoiceInfoService.getTopInvoiceByUser(ResourceUtil.getSessionUserName().getUserName(),"",10));
//        map.put("dedInvoice", cbsInvoiceInfoService.getTopInvoiceByUser(ResourceUtil.getSessionUserName().getUserName(),"dedicated",10));
        return WX_PREFIX+"procurement/invoice";
    }

    @RequestMapping(params = "getInvoice")
    @ResponseBody
    public List<CbsInvoiceInfoEntity> getInvoice(String type){
        ZyContactsEntity ct = zyContactsService.findContactByUserName(ResourceUtil.getSessionUserName().getUserName());
        if(ct != null && ct.getBelongCinema() != null){
            return cbsInvoiceInfoService.getTopInvoiceByCinema(ct.getBelongCinema().getId(),type,10);
        }
        return new ArrayList<CbsInvoiceInfoEntity>();
    }

    @RequestMapping(params = "goEquipChose")
    public String goEquipChose(String cinemaId,ModelMap modelMap){
        modelMap.put("cinemaId",cinemaId);
        return WX_PREFIX + "procurement/equip-list";
    }

    @RequestMapping(params = "confirmProcurement",method = RequestMethod.POST)
    @ResponseBody
    public ProcurementNote confirmProcurement(ProcurementNote note,HttpServletRequest request){
        note = shoppingCarService.orderFromCar(note,(String)request.getSession().getAttribute("openId"));
        if(null == ResourceUtil.getSessionUserName()){
            wxCommonService.initUserWithPhoneAndName(note.getContactPhone(),note.getContactName(),request);
        }
        return note;
    }

    @RequestMapping(params = "goChooseContacts")
    public ModelAndView goChooseContacts(ModelMap map){
        ModelAndView mv = new ModelAndView(WX_PREFIX+"procurement/choose-contact");
        if(ResourceUtil.getSessionUserName() != null){
            mv.addObject("cts",zyCommonAddressService.getAddressByUser(ResourceUtil.getSessionUserName().getUserName()));
        }
        return mv;
    }

}
